package com.totcy.atom.model;

import android.annotation.SuppressLint;
import android.content.Context;

import com.totcy.atom.BuildConfig;
import com.totcy.atom.CommonValues;
import com.totcy.atom.bean.AppVersion;
import com.totcy.atom.bean.User;
import com.totcy.atom.net.HttpManager;
import com.totcy.atom.net.subscriber.BaseHttpSubscriber;
import com.totcy.baselibrary.base.mvpbase.BaseModelImpl;
import com.totcy.atom.presenter.contract.CheckUpdateContract;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class CheckUpdateModel extends BaseModelImpl implements CheckUpdateContract.Model {

    BaseHttpSubscriber<AppVersion> subscriber;

    public CheckUpdateModel(Context context) {
        super(context);
    }

    @Override
    public void doCheckUpdate(final DataCallback callback) {
        HttpManager.getApiService(mContext)
                .checkUpdate(CommonValues.CHECK_APP_UPDATE)
                .compose(HttpManager.<AppVersion>applySchedulers())
                .compose(HttpManager.<AppVersion>handleResult())
                .subscribe(subscriber = new BaseHttpSubscriber<AppVersion>() {
                    @Override
                    public void onSuccess(AppVersion appVersion) {
                        //新版本判断
                        if (appVersion.getVersionCode() > BuildConfig.VERSION_CODE) {
                            callback.onUpdateInfo(appVersion);
                        }
                    }

                    @Override
                    public void onError(int code, String errorMsg) {

                    }
                });
    }

    @SuppressLint("CheckResult")
    @Override
    public void downloadApk(final String downloadUrl, final DataCallback callback) {

        File parent = new File(mContext.getExternalCacheDir() ,"apk");
        if(!parent.exists()){
            parent.mkdir();
        }
        final File file = new File(parent,"AtomApp.apk");


        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> observableEmitter) throws Exception {
                observableEmitter.onNext(0);

                OkHttpClient okHttpClient = new OkHttpClient();
                Request request = new Request.Builder()
                        .get()
                        .url(downloadUrl)
                        .addHeader("Accept-Encoding", "identity")
                        .build();
                Call call = okHttpClient.newCall(request);
                try {
                    Response response = call.execute();
                    long lenth = response.body().contentLength();

                    //将响应数据转化为输入流数据
                    InputStream inputStream = response.body().byteStream();

                    OutputStream os = new FileOutputStream(file);

                    long sum = 0;
                    int bytesRead;
                    byte[] buffer = new byte[4096];
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        os.write(buffer, 0, bytesRead);

                        sum += bytesRead;
                        int progress = (int) (sum * 1.0f / lenth * 100);
                        // 下载中
                        observableEmitter.onNext(progress);
                    }
                    //下载完成
                    observableEmitter.onComplete();

                    os.flush();
                    os.close();
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer progress) throws Exception {
                        callback.onDownloadProgress(progress);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        callback.onDownloadFinish(file);
                    }
                });
    }

    @Override
    public void canCelRequest() {
        if (subscriber != null) {
            subscriber.unSubscribe();
        }
    }
}
